//
//  UITableView+CBTableViewDataSource.m
//  CedarFinancePH
//
//  Created by lshenrong on 2018/3/20.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import <objc/runtime.h>
#import "UITableView+CedarTableViewExtend.h"
#import "CedarBaseTableViewDataSource.h"
#import "CedarTableViewDataSourceMaker.h"
#import "CedarTableViewSectionMaker.h"
#import "CedarBaseTableViewCell.h"

//static NSString * getIdentifier (){
//    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
//    CFStringRef uuidStrRef = CFUUIDCreateString(NULL, uuidRef);
//    CFRelease(uuidRef);
//    NSString * retStr = (__bridge NSString *) uuidStrRef;
//    CFRelease(uuidStrRef);
//    return retStr;
//}

static const char *kTableViewDataSourcePropertyKey = "kTableViewDataSourceKey";


@implementation UITableView (CBTableViewDataSource)

//定义属性
- (CedarBaseTableViewDataSource *)cbTableViewDataSource {
    return objc_getAssociatedObject(self,kTableViewDataSourcePropertyKey);
}

- (void)setCbTableViewDataSource:(CedarBaseTableViewDataSource *)cbTableViewDataSource {
    objc_setAssociatedObject(self,kTableViewDataSourcePropertyKey,cbTableViewDataSource,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)cedar_makeSectionWithData:(NSArray *)data {
    NSMutableDictionary * delegates = [[NSMutableDictionary alloc] init];
    CedarTableViewSectionMaker *make = [[CedarTableViewSectionMaker alloc] init];
    make.data(data);
    make.cell([UITableViewCell class]);
    [self registerClass:make.section.cell forCellReuseIdentifier:make.section.identifier];
    make.section.tableViewCellStyle = UITableViewCellStyleDefault;
    for(NSUInteger i = 0;i<data.count;i++) {
        if(data[i][@"detail"]) {
            make.section.tableViewCellStyle = UITableViewCellStyleSubtitle;
            break;
        }
        if(data[i][@"value"]) {
            make.section.tableViewCellStyle = UITableViewCellStyleValue1;
            break;
        }
    }
    id<CedarBaseTableViewDataSourceProtocol> ds = (id<CedarBaseTableViewDataSourceProtocol>)[[CBSampleTableViewDataSource alloc]init];
    if(!self.tableFooterView) {
        self.tableFooterView = [[UIView alloc] init];
    }
    ds.sections = [@[make.section] mutableCopy];
    ds.delegates = delegates;
    self.cbTableViewDataSource = ds;
    self.dataSource = ds;
    self.delegate = ds;
}

//数据带有cell 设置高度
- (void)cedar_makeSectionWithData:(NSArray *)data andCellClass:(Class)cellClass rowHeight:(CGFloat)height{
    [self cedar_makeDataSource:^(CedarTableViewDataSourceMaker * make) {
        [make makeSection:^(CedarTableViewSectionMaker * section) {
            section.data(data);
            section.cell(cellClass);
            section.adapter(^(CedarBaseTableViewCell *cell,id rowData,NSUInteger index) {
                if ([cell respondsToSelector:@selector(configureCellData:index:)]) {
                    [cell configureCellData:rowData index:index];
                }else{
                    CDebugLog(@"warning: %@ must be inherit CedarBaseTableViewCell",NSStringFromClass([cell class]));
                }
            });
            section.event(^(NSUInteger index,id data){
                CDebugLog(@"event index:%lu,data:%@",(unsigned long)index,data);
            });
            if(height>0){
                section.height(height);
            }else{
                section.autoHeight();
            }
        }];
    }];
}



- (void)cedar_makeSectionWithData:(NSArray *)data
                     andCellClass:(Class)cellClass
                       eventBlock:(EventBlock)cellClick
                        rowHeight:(CGFloat)height{
    [self cedar_makeDataSource:^(CedarTableViewDataSourceMaker * make) {
        [make makeSection:^(CedarTableViewSectionMaker * section) {
            section.data(data);
            section.cell(cellClass);
//            
//            section.headerView(^{
//                UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
//                view.backgroundColor = [UIColor greenColor];
//                return view;
//            });
            
            section.adapter(^(CedarBaseTableViewCell *cell,id rowData,NSUInteger index) {
                if ([cell respondsToSelector:@selector(configureCellData:index:)]) {
                    [cell configureCellData:rowData index:index];
                }else{
                    CDebugLog(@"warning: %@ must be inherit CedarBaseTableViewCell",NSStringFromClass([cell class]));
                }
            });
            section.event(^(NSUInteger index,id data){
                CDebugLog(@"event index:%lu,data:%@",(unsigned long)index,data);
                if (cellClick) {
                    cellClick(index,data);
                }
            });
            if(height>0){
                section.height(height);
            }else{
                section.autoHeight();
            }
        }];
    }];
}




/**
 初始

 @param maker maker description
 */
- (void)cedar_makeDataSource:(void(^)(CedarTableViewDataSourceMaker * make))maker {
    CedarTableViewDataSourceMaker * make = [[CedarTableViewDataSourceMaker alloc] initWithTableView:self];
    maker(make);
    Class DataSourceClass = [CedarBaseTableViewDataSource class];
    NSMutableDictionary * delegates = [[NSMutableDictionary alloc] init];
    
    /*if(make.commitEditingBlock||make.scrollViewDidScrollBlock) {
        DataSourceClass = objc_allocateClassPair([CBBaseTableViewDataSource class], [getIdentifier() UTF8String],0);
        if(make.commitEditingBlock) {
            class_addMethod(DataSourceClass,NSSelectorFromString(@"tableView:commitEditingStyle:forRowAtIndexPath:"),(IMP)commitEditing,"v@:@@@");
            delegates[@"tableView:commitEditingStyle:forRowAtIndexPath:"] = make.commitEditingBlock;
        }
        if(make.scrollViewDidScrollBlock) {
            class_addMethod(DataSourceClass,NSSelectorFromString(@"scrollViewDidScroll:"),(IMP)scrollViewDidScroll,"v@:@");
            delegates[@"scrollViewDidScroll:"] = make.scrollViewDidScrollBlock;
        }
    }*/
    
    if(!self.tableFooterView) {
        self.tableFooterView = [UIView new];
    }
    
    id<CedarBaseTableViewDataSourceProtocol> ds = (id<CedarBaseTableViewDataSourceProtocol>) [DataSourceClass  new];
    ds.sections = make.sections;
    ds.delegates = delegates;
    self.cbTableViewDataSource = ds;
    self.dataSource = ds;
    self.delegate = ds;
}






@end

static void commitEditing(id self, SEL cmd, UITableView *tableView,UITableViewCellEditingStyle editingStyle,NSIndexPath * indexPath)
{
    CedarBaseTableViewDataSource * ds = self;
    void(^block)(UITableView *,UITableViewCellEditingStyle ,NSIndexPath * ) = ds.delegates[NSStringFromSelector(cmd)];
    if(block) {
        block(tableView,editingStyle,indexPath);
    }
}

static void scrollViewDidScroll(id self, SEL cmd, UIScrollView * scrollView) {
    CedarBaseTableViewDataSource * ds = self;
    void(^block)(UIScrollView *) = ds.delegates[NSStringFromSelector(cmd)];
    if(block) {
        block(scrollView);
    }
};
